package com.turing.java.jvm.concurrent.sync.images;

import org.openjdk.jol.info.ClassLayout;

/**
 * 由于虚拟机内部会调用 10 多个线程，因此偏向锁大约在 JVM 启动五秒钟后才能启动，避免
 * 启动阶段造成大量的锁竞争。
 */
public class HeavyWeightMonitor {

    public static void main(String[] args) throws InterruptedException {
        Thread.sleep(5000);
        Object a = new Object();

        Thread thread1 = new Thread() {
            @Override
            public void run() {
                synchronized (a) {
                    System.out.println("thread1 locking");
                    System.out.println(ClassLayout.parseInstance(a).toPrintable());
                    try {
                        //让线程晚点儿死亡，造成锁的竞争
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread thread2 = new Thread() {
            @Override
            public void run() {
                synchronized (a) {
                    System.out.println("thread2 locking");
                    System.out.println(ClassLayout.parseInstance(a).toPrintable());
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread1.start();
        thread2.start();
    }

}
